<template>
  <drag-dialog title="数据设置" v-model="showDialog" @close="close">
    <div class="dict-container">
      <div class="header">
        <div>数据来源:</div>
        <el-radio-group v-model="localData.dicOption" @change="handleTypeClick">
          <el-radio v-for="opt in typeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-radio-group>
      </div>
      <div class="content">
        <el-form label-position="right" label-width="100px" label-suffix=":">
          <template v-if="localData.dicOption == 'static'">
            <el-form-item label="数据选项">
              <div>
                <draggable
                  tag="ul" :list="localData.dicData" :group="{ name: 'dic' }" ghost-class="ghost"
                  handle=".drag-item" class="drag-list">
                  <template #item="{ element, index }">
                    <li>
                      <el-icon class="el-icon drag-item drag-icon">
                        <Operation />
                      </el-icon>
                      <el-input
                        style="margin-right: 5px" size="default" clearable v-model="element.label"
                        placeholder="label" />
                      <el-input size="default" clearable v-model="element.value" placeholder="value" />
                      <el-button
                        @click="handleRemoveFields(index)" circle plain type="danger" size="small"
                        icon="el-icon-minus" style="margin-left: 5px" />
                    </li>
                  </template>
                </draggable>
                <div class="operation">
                  <el-button link @click="handleAddFields(localData.dicData)">添加列 </el-button>
                  <el-button link @click="batchAdd(localData.dicData)">批量编辑 </el-button>
                  <option-ref v-if="localData.type !== 'checkbox'" :data="localData" :formJson="options" />
                  <connect-more
                    v-if="localData.type !== 'checkbox'" :data="localData"
                    :notSavedOptions="notSavedOptions" :formJson="options" />
                </div>
              </div>
            </el-form-item>

          </template>
          <template v-if="localData.dicOption == 'dictionary'">
            <el-form-item label="选择字典">
              <el-select
                v-model="localData.dictionary" placeholder="值集筛选" size="default"
                @change="handleDictionaryChange" style="width: 400px" filterable>
                <el-option
                  v-for="item in optionsDictionary" :key="item.dictType" :label="item.dictName"
                  :value="item.dictType" />
              </el-select>
            </el-form-item>
          </template>
          <template v-if="localData.dicOption == 'remote'">
            <custom-ajax-setting
              v-model="localData" :options="options"
              :props="ajaxSettingProps" />
            <el-form-item label="返回结构层次">
              <el-input v-model="localData.dicRes" placeholder="默认为res" style="width: 400px" clearable />
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>
    <template #footer>
      <dialog-footer @ok="submit" @cancel="close" />
    </template>

    <batch-add
      v-model:showDialog="showBatchAdd" v-model:data="localData" @close="handleBatchSubmit"
      :oldDiceStr="oldDictStr" />
  </drag-dialog>
</template>

<script>
import Draggable from 'vuedraggable'
import batchAdd from './batchAddFile.vue'
import OptionRef from './optionRef.vue'
import connectMore from './connectMore.vue'
import customAjaxSetting from './customAjaxSetting.vue'
import { searchAll } from '@base/api/base/dict/type'
import { cloneDeep } from 'lodash-es'

export default {
  components: { Draggable, batchAdd, OptionRef, connectMore, customAjaxSetting },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => { }
    },
    options: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      showDialog: false,
      showBatchAdd: false,
      localData: {},
      typeOptions: [
        { label: '静态数据', value: 'static' },
        { label: '字典数据', value: 'dictionary' },
        { label: '远端数据', value: 'remote' }
      ],
      oldDictStr: '',
      optionsDictionary: [],
      ajaxSettingProps: {
        type: 'remoteType',
        url: 'formDataUrl',
        // params: 'dicQueryConfig'
      }
    };
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.showDialog = newVal;
        if (newVal) {
          this.localData = cloneDeep(this.data);
        }
      },
      immediate: true
    },
    showDialog: {
      handler(newVal) {
        this.$emit('update:modelValue', newVal);
      }
    },
    data: {
      handler(val) {
        // this.localData = cloneDeep(val);
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getDictionary()
  },
  methods: {
    getDictionary() {
      let params = {
        orderBy: 'UPDATE_TIME',
        sortDirect: 'DESC'
      }
      searchAll(params).then((res) => {
        this.optionsDictionary = res.data
      })
    },
    handleDictionaryChange(e) {
      this.getDicts(e).then((response) => {
        response.data.map((item, index) => {
          item.value = item.dictValue
          item.label = item.dictLabel
          item.desc = ''
          item.connectChild = [
            {
              childValue: [],
              childdataList: [],
              childprop: ''
            }
          ]
        })
        this.localData.dicData = response.data
      })
    },
    submit() {
      this.$emit('submit', this.localData);
      this.close();
    },
    close() {
      this.showDialog = false;
    },
    handleRemoveFields(index) {
      this.localData.dicData.splice(index, 1)
    },
    handleAddFields(data) {
      const i = data.length + 1
      const col = data.length ? Number(data[data.length - 1].value) + 1 : 0
      if (!this.localData.dicData) {
        this.localData.dicData = [
          {
            label: `选项${i}`,
            value: `${col}`,
            compsRef: []
          }
        ]
      } else {
        this.localData.dicData.push({
          label: `选项${i}`,
          value: `${col}`,
          compsRef: []
        })
      }
    },
    batchAdd(data) {
      let oldDict = []
      data.forEach((element) => {
        oldDict.push(element.label)
      })
      this.oldDictStr = oldDict.join('\n')
      this.showBatchAdd = true
    },
    handleBatchSubmit(data) {
      this.localData.dicData = data
    },
    handleTypeClick(name) {
      this.resetSelectSetting()

      if (name == 'remote') {
        this.localData.dicRes = 'res.data'
        this.localData.remoteType = 'ajax'
        // this.localData.dicContentType = 'formData'
        // this.localData.dicMethod = 'post'
      }
      if (name == 'static') {
        this.localData.dicData = [
          {
            label: '选项一',
            value: '0',
            connectChild: [
              {
                childValue: [],
                childdataList: [],
                childprop: ''
              }
            ]
          },
          {
            label: '选项二',
            value: '1',
            connectChild: [
              {
                childValue: [],
                childdataList: [],
                childprop: ''
              }
            ]
          },
          {
            label: '选项三',
            value: '2',
            connectChild: [
              {
                childValue: [],
                childdataList: [],
                childprop: ''
              }
            ]
          }
        ]
      } else if (name == 'dictionary') {
        this.localData.dictionary = undefined
        this.localData.props = {
          label: 'dictLabel',
          value: 'dictValue'
        }
      }
    },
    // 切换类型时重置配置
    resetSelectSetting() {
      delete this.localData.dictionary
      delete this.localData.dicRes
      //   delete this.localData.dicUrl
      delete this.localData.formDataUrl
      delete this.localData.dicContentType
      delete this.localData.ajaxModel
      delete this.localData.ajaxApi
      this.localData.dicData = []
      this.localData.dicQueryConfig = []
      this.localData.props = {
        label: 'label',
        value: 'value',
        desc: 'desc'
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.dict-container {
  width: 100%;

  .header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }

  .content {
    width: 100%;
    height: 500px;
    overflow: auto;
    border: 1px solid rgb(220 223 230);
    padding: 8px 24px;

    .drag-list {
      max-height: 300px;
      overflow: auto;

      li {
        display: flex;
        align-items: center;
        width: 50%;
        margin: 4px 0;

        .drag-icon {
          font-size: 16px;
          margin: 0 5px;
          cursor: move;
        }
      }
    }

    .operation {
      margin-left: 70px;
      display: flex;
      gap: 20px;
    }

    .key-item {
      display: flex;
      align-items: center;
      width: 50%;
      margin: 4px 0;
    }

  }
}
</style>
